<template>
  <div style="width: 100%" :class="props.border ? 'relation-config' : ''">
    <div v-for="(item, index) in relations" :key="index" class="relation-item">
      <el-select
        v-model="item.fk"
        placeholder="外键字段"
        filterable
        clearable
        style="width: 20%; margin-right: 10px"
      >
        <el-option
          v-for="field in tableFields"
          :key="field.value"
          :label="field.label"
          :value="field.value"
        />
      </el-select>

      <el-select
        v-model="item.connect"
        placeholder="数据库连接"
        @change="handleConnectChange(index)"
        clearable
        style="width: 20%; margin-right: 10px"
      >
        <el-option
          v-for="item in dbConnections"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <el-select
        v-model="item.relative_name"
        placeholder="关联表"
        filterable
        clearable
        @change="handleTableChange(index)"
        style="width: 20%; margin-right: 10px"
      >
        <el-option
          v-for="item in tables[index]"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>

      <el-select
        v-model="item.pk"
        clearable
        placeholder="关联键"
        style="width: 20%; margin-right: 10px"
      >
        <el-option
          v-for="column in columns[index]"
          :key="column.value"
          :label="column.label"
          :value="column.value"
        />
      </el-select>

      <el-select
        v-model="item.fields"
        multiple
        clearable
        placeholder="查询字段"
        style="width: 20%; margin-right: 10px"
      >
        <el-option
          v-for="column in columns[index]"
          :key="column.value"
          :label="column.label"
          :value="column.value"
        />
      </el-select>

      <el-button
        v-if="relations.length > 1"
        type="danger"
        icon="Close"
        @click="removeRelation(index)"
      />
    </div>

    <div class="actions">
      <el-button type="primary" @click="addRelation">添加关系</el-button>
      <el-button @click="clearRelations">清空配置</el-button>
    </div>
  </div>
</template>

<script setup>
/**
 * 这是一个用于定义表与表之间连接的组件
 */
import ActionAPI from '@/api/admin/dev/action';

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  tableFields: {
    type: Array,
    default: () => [],
  },
  dbConnections: {
    type: Array,
    default: () => [],
  },
  border: {
    type: Boolean,
    default: true,
  },
});

const emit = defineEmits(['update:modelValue']);

// 初始化关系配置项
const initRelation = () => ({
  fk: null,
  connect: '',
  relative_name: '',
  pk: null,
  fields: [],
});

// 数据存储
const relations = ref(
  props.modelValue.length ? [...props.modelValue] : [initRelation()],
);
const tables = ref({}); // 缓存各索引对应的表列表
const columns = ref({}); // 缓存各索引对应的列列表

// 同步数据到父组件
watch(relations, (val) => emit('update:modelValue', val), { deep: true });

// 添加新关系
const addRelation = () => {
  relations.value.push(initRelation());
  tables.value[relations.value.length - 1] = [];
  columns.value[relations.value.length - 1] = [];
};

// 删除关系
const removeRelation = (index) => {
  relations.value.splice(index, 1);
  delete tables.value[index];
  delete columns.value[index];
};

// 清空配置
const clearRelations = () => {
  relations.value = [initRelation()];
  tables.value = {};
  columns.value = {};
};

// 数据库连接变化时加载表列表
const handleConnectChange = async (index) => {
  const conn = relations.value[index].connect;
  ActionAPI.getRelationTabls({ conn }).then(({ data }) => {
    tables.value[index] = data;
  });
  relations.value[index].relative_name = '';
  columns.value[index] = [];
};

// 表名变化时加载字段列表
const handleTableChange = async (index) => {
  const conn = relations.value[index].connect;
  const table = relations.value[index].relative_name;
  ActionAPI.getRelationFields({ conn, table }).then(({ data }) => {
    columns.value[index] = data;
  });
};
</script>

<style scoped>
.relation-config {
  border: 1px solid #ebeef5;
  padding: 15px;
  border-radius: 4px;
}

.relation-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.actions {
  margin-top: 15px;
}
</style>
